package com.stms.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.stms.dao.UserDao;
import com.stms.bean.User;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        // Basic validation
        if (!password.equals(confirmPassword)) {
            request.setAttribute("error", "密码不一致，请重新输入。");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        // Create a new User object and save it to the database
        User user = new User(username, password);
        user.setUserName(username);
        user.setPassWord(password);
        user.setRank(1);
        UserDao userDao = new UserDao();
        boolean success = userDao.addUser(user);

        if (success) {
            HttpSession session = request.getSession();
            session.setAttribute("successMessage", "您已成功注册，请登录。"); // 将成功消息存入session
            // Redirect to index.jsp after successful registration
            response.sendRedirect("login.jsp");
        } else {
            request.setAttribute("error", "注册失败，请重试。");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
}